package com.ewei.support.javax.mail.util;

import javax.mail.Part;
import javax.mail.internet.InternetHeaders;

import org.budo.support.lang.util.ReflectUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

import com.sun.mail.imap.IMAPBodyPart;

/**
 * @author limingwei
 */
public class MailPartHeaderUtil {
    private static final Logger log = Slf4j.getLogger();

    public static void setHeader(Part part, String header_name, String header_value) {
        if (null == part) {
            log.warn("setHeader, part is null");
            return;
        }

        if (part instanceof IMAPBodyPart) {// com.sun.mail.imap.IMAPBodyPart // IMAPMessage
            setHeaderByReflect(part, header_name, header_value);
        } else {
            try {
                part.setHeader(header_name, header_value);
            } catch (Throwable e) {
                log.error("part.setHeader error, " + e);
                setHeaderByReflect(part, header_name, header_value);
            }
        }
    }

    private static void setHeaderByReflect(Part part, String header_name, String header_value) {
        if (null == part) {
            log.warn("setHeaderByReflect, part is null");
            return;
        }

        try {
            InternetHeaders headers = (InternetHeaders) ReflectUtil.getFieldValue(part, "headers");
            headers.setHeader(header_name, header_value);
        } catch (Throwable e) {
            log.error("part.setHeaderByReflect error, " + e);
        }
    }
}